<?php
/**
 * Created by PhpStorm.
 * User: xpz
 * Date: 2021/5/17
 * Time: 9:05
 */

namespace app\common\model;
use think\Model;
use app\common\model\Chatvisitorlog;

use fast\Tool;

class Chatvisitor extends Model
{
    protected $name = "chat_visitor";

    /**
     * 添加游客记录
     * @param $params
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function Record($params)
    {
        $where['uuid'] = $params['uuid'];
        if (!self::where($where)->find()) {
            $data['uuid'] = $params['uuid'];
            $data['company_id'] = $params['company_id'];
            $data['user_id'] = isset($params['user_id']) ? $params['user_id'] : 0;
            $data['head_img'] = "/assets/client/img/head_" . rand(1, 2) . ".png";
            $data['add_time'] = time();
            $data['status'] = isset($params['status']) ? $params['status'] :'1';
            self::create($data);
            $id = self::getLastInsID();
            self::where($where)->update(['nick_name' => '游客#' . $id]);
        }
        if (!Chatvisitorlog::where($where)->whereTime('add_time', 'today')->find()) {
            $data_['uuid'] = $params['uuid'];
            $data_['join_ip'] = $params['join_ip'];
            $data_['screen_size'] = $params['screen_size'];
            $data_['device_info'] = $params['device_info'];
            $data_['user_agent'] = isset($params['user_agent']) ? $params['user_agent'] : '';
            $arr = Tool::getTaobaoArea($data_['join_ip']);
            if ($arr) {
                $data_['country'] = $arr['country'];
                $data_['province'] = $arr['province'];
                $data_['city'] = $arr['city'];
            }
            $data_['add_time'] = time();
            Chatvisitorlog::create($data_);
        }
    }

    /**
     * @param $uuid
     * @param $status
     * @return Chatvisitor
     */
    public static function updateOffOn($uuid, $status)
    {
        return self::where('uuid', $uuid)->update(['status' => $status]);
    }
}